package com.dnjn.happiness.system.controller;

import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.core.constant.UserConstants;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.system.api.model.TeamTreeSelectVO;
import com.dnjn.happiness.system.api.model.TreeSelectVO;
import com.dnjn.happiness.system.domain.vo.TeamTreeSelect;
import com.dnjn.happiness.system.domain.vo.TreeSelect;
import com.dnjn.happiness.system.service.ISysDeptService;
import com.dnjn.happiness.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门信息
 *
 * @author happy
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;


    @InnerAuth
    @GetMapping("/getTeamTreeByDeptId/{deptId}")
    public R<List<TeamTreeSelect>> getTeamTreeByDeptId(@PathVariable Long deptId){
        List<TeamTreeSelect> treeSelectList = deptService.getTeamTreeByDeptId(deptId);
        return R.ok(treeSelectList);
    }


    @InnerAuth
    @PostMapping("/selectTeamTreeList")
    public R<List<TeamTreeSelect>> selectTeamTreeList(@RequestBody SysDept dept){
        List<TeamTreeSelect> treeSelectList = deptService.selectTeamTreeList(dept);
        return R.ok(treeSelectList);
    }


    @InnerAuth
    @GetMapping("/selectSuperDeptList/{userId}")
    public R<SysDept> selectSuperDeptList(@PathVariable Long userId){
        return R.ok(deptService.selectSuperDeptList(userId));
    }



    /**
     *
     */
    @InnerAuth
    @GetMapping("/selectDeptByChildUserId/{deptId}")
    public R<SysDept> selectDeptByChildUserId(@PathVariable Long deptId) {
        return R.ok(deptService.selectDeptByChildUserId(deptId));
    }

    /**
     * 获取子部门列表
     */
    @InnerAuth
    @GetMapping("/getChildDeptListById/{deptId}")
    public R<List<SysDept>> getChildDeptListById(@PathVariable Long deptId) {
        List<SysDept> depts = deptService.getChildDeptListById(deptId);
        return R.ok(depts);
    }

    @InnerAuth
    @GetMapping("/getDeptTreeApi")
    public R<List<TreeSelectVO>> getDeptTreeApi(SysDept dept) {
        List<TreeSelect> selectList = deptService.selectDeptTreeList(dept);
        List<TreeSelectVO> selectVOList = new ArrayList<>();
        selectList.forEach(item->{
            TreeSelectVO treeSelectVO = new TreeSelectVO();
            BeanUtils.copyBeanProp(treeSelectVO,item);
            selectVOList.add(treeSelectVO);
        });
        return R.ok(selectVOList);
    }


    /**
     * 获取部门下所有子部门
     */
    @InnerAuth
    @GetMapping("/getDeptListByDeptId")
    public R<List<SysDept>> getDeptListByDeptId(@PathVariable Long deptId) {
        List<SysDept> depts = deptService.getDeptListByDeptId(deptId);
        return R.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @InnerAuth
    @GetMapping(value = "/getListAll")
    public R<List<Long>> getListAll() {
        return R.ok(deptService.getListAll());
    }

    /**
     * 根据部门编号获取详细信息
     */
    @InnerAuth
    @GetMapping(value = "/getInfoById/{deptId}")
    public R<SysDept> getInfoById(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门列表
     */
    @InnerAuth
    @GetMapping("/selectDeptList")
    public R<List<SysDept>> selectDeptList(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(depts);
    }
    /**
     * 获取部门列表
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        Long leaderId = dept.getLeaderId();
        SysUser sysUser = userService.selectUserInfo(leaderId);
        if (null != sysUser) {
            dept.setLeaderName(userService.selectUserInfo(leaderId).getNickName());
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        int i = deptService.insertDept(dept);
        //更新leader的部门id
        if (null != sysUser) {
            sysUser.setDeptId(dept.getDeptId());
            userService.updateUser(sysUser);
        }
        return toAjax(i);
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！");
        }
        Long leaderId = dept.getLeaderId();
        SysUser sysUser = userService.selectUserInfo(leaderId);
        if (null != sysUser) {
            dept.setLeaderName(userService.selectUserInfo(leaderId).getNickName());
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        int i = deptService.updateDept(dept);
        //更新leader的部门id
        if (null != sysUser) {
            sysUser.setDeptId(dept.getDeptId());
            userService.updateUser(sysUser);
        }
        return toAjax(i);
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 获取当前用户下的部门
     */
    @Operation(summary = "获取当前用户下的部门")
    @GetMapping("/getDeptListByLeaderId/{leaderId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getDeptListByLeaderId(@PathVariable Long leaderId) {
        Assert.notNull(leaderId, "leaderId不能为空！");
        SysDept dept = deptService.getDeptByLeaderId(leaderId);
        if (null == dept) {
            return error("未查询到上级机构信息");
        }

        //查询当前部门下一级的部门
        List<SysDept> sysDeptList = deptService.getBelowDeptListByDeptId(dept.getDeptId());

        return success(sysDeptList);
    }


    /**
     * 获取部门树列表
     */
//    @RequiresPermissions("@ss.hasPermi('system:dept:query')")
    @Operation(summary = "获取部门树列表")
    @GetMapping("/getDeptTreeAdmin")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getDeptTreeAdmin(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @Operation(summary = "获取下级部门列表")
    @GetMapping("/getDeptList")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getDeptTree(SysDept dept) {
        return success(deptService.getDeptList(dept));
    }

}
